package com.douxg.learning.worktest.yxaq.dp;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.*;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Redis 工具类
 */
public class RedisUtil {

    private static Logger _log = LoggerFactory.getLogger(RedisUtil.class);

    // 在borrow一个jedis实例时，是否提前进行validate操作；如果为true，则得到的jedis实例均是可用的；
    private static boolean TEST_ON_BORROW = false;

    private static JedisPool jedisPool = null;
    private static JedisCluster jedisCluster = null;

    protected static final int DEFAULT_TIMEOUT = 2000;
    protected static final int DEFAULT_MAX_REDIRECTIONS = 5;
    private static String redisType;
    private static JedisPoolConfig config;
    private static String PASSWORD;

    /**
     * 初始化Redis连接池
     */
    private static void initialPool(String ip, int port, int timeout) {
        try {
            jedisPool = new JedisPool(config, ip, port, timeout);
        } catch (Exception e) {
            _log.error("First create JedisPool error : " + e);
        }
    }

    private static void initialCluster(String ip, String password, int timeout) {
        try {

            String[] clusterIps = ip.split("[|]");
            Set<HostAndPort> nodes = new LinkedHashSet<HostAndPort>();
            for (String clusterIp : clusterIps) {
                String[] ipProt = clusterIp.trim().split(":");
                nodes.add(new HostAndPort(ipProt[0].trim(), Integer.valueOf(ipProt[1].trim())));
            }
            if (!StringUtils.isEmpty(password)) {
                jedisCluster = new JedisCluster(nodes, timeout, DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, password, config);
            } else {
                jedisCluster = new JedisCluster(nodes, timeout, DEFAULT_TIMEOUT, DEFAULT_MAX_REDIRECTIONS, config);
            }
        } catch (Exception e) {
            _log.error("First create JedisPool error : " + e);
        }
    }

    /**
     * 在多线程环境同步初始化
     */
    public static synchronized void poolInit(String ip, String password, int port, int timeout, int maxActive, int maxIdle, int maxWait) {
        config = new JedisPoolConfig();
        config.setMaxTotal(maxActive);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWait);
        config.setTestOnBorrow(TEST_ON_BORROW);
        String[] clusterIps = ip.split("[|]");
        PASSWORD = password;
        if (clusterIps.length == 1) {
            redisType = "noCluster";
        } else {
            redisType = "cluster";
        }
        if (null == jedisPool && "noCluster".equals(redisType)) {
            initialPool(ip, port, timeout);
        }

        if (null == jedisCluster && "cluster".equals(redisType)) {
            initialCluster(ip, password, timeout);
        }
    }

    /**
     * 同步获取Jedis实例
     *
     * @return Jedis
     */
    public synchronized static JedisCommands getJedis() {
        JedisCommands jedisCommands = null;
        if (null != jedisPool) {
            try {
                Jedis jedis = jedisPool.getResource();
                if (!StringUtils.isEmpty(PASSWORD)) {
                    jedis.auth(PASSWORD);
                }
                jedisCommands = jedis;
            } catch (Exception e) {
                _log.error("Get jedis error : " + e);
            }
        }

        if (null != jedisCluster) {
            jedisCommands = jedisCluster;
        }

        return jedisCommands;
    }

    public static void close(JedisCommands jedis) {
        if (null != jedisPool && "noCluster".equals(redisType)) {
            ((Jedis) jedis).close();
        }
    }


    /**
     * 获取String值
     *
     * @param key
     * @return value
     */
    public synchronized static String hget(String key, String key1) {
        JedisCommands jedis = getJedis();
        if (null == jedis) {
            return null;
        }
        String value = jedis.hget(key, key1);
        close(jedis);
        return value;
    }


}
